package com.beiyou.aop;

import cn.hutool.core.util.ObjectUtil;
import com.beiyou.dto.PageInfo;
import com.beiyou.local.PageInfoLocal;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author wzby
 * @Date: 2022/10/17 17:32
 */
@Component
@Aspect
public class DaoAop {
    //通过注解方式定义切入点
    @Pointcut("@annotation(com.beiyou.annotation.PageNote)")
    public void point() {}

    @Around("point()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {


        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        if (ObjectUtil.isNotEmpty(pageSize)){
            int page_num = 1;
            if (ObjectUtil.isNotEmpty(pageNum)){
                page_num = Integer.valueOf(pageNum);
            }
            int page_size = Integer.valueOf(pageSize);
            PageHelper.startPage(page_num,page_size);
        }
        //调用目标方法
        Object daoValue = proceedingJoinPoint.proceed();
        if (daoValue instanceof Page) {
            Page page = (Page)daoValue;
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPages(page.getPages());
            pageInfo.setTotal(page.getTotal());
            PageInfoLocal.set(pageInfo);
        }

        return daoValue;
    }
}
